<template>
  <Dialog
    @open="handleDialogOpen"
    @close="handleDialogClose"
    @handle-confirm="handleConfirm"
  >
    <div class="top">
      <div class="left">
        <el-scrollbar>
          <el-tree
            ref="tree"
            node-key="id"
            :data="data"
            :props="defaultProps"
            :expand-on-click-node="false"
            :default-expanded-keys="defaultExpandedKeys"
            :highlight-current="true"
            @node-expand="nodeExpand"
            @node-collapse="nodeCollapse"
            @current-change="treeCurrentChange"
          >
            <template #default="{ node }">
              <span
                class="treeNode"
              >
                <p
                  class="title"
                  :title="node.label"
                >
                  {{ node.label }}
                </p>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="right">
        <el-scrollbar>
          <div class="users">
            <div
              :class="['user',checkedUsers.findIndex(e => e.id===user.id)>=0?'checked':'' ]"
              v-for="user in users"
              :key="user.id"
              @click="selectUser(user)"
            >
              <span class="sign">
                <el-icon
                  color="#ffffff"
                  v-if="checkedUsers.findIndex(e => e.id===user.id)>=0"
                ><check /></el-icon>
              </span>
              <p class="name">
                {{ user.name }}
              </p>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <div
      class="bottom"
      v-if="checkedUsers.length"
    >
      <p class="name">
        已选{{ checkedUsers.length }}名用户：
      </p>
      <div class="checkedUsers">
        <el-tag
          class="checkedUser"
          v-for="user in checkedUsers"
          :key="user.id"
        >
          {{ user.name }}
        </el-tag>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { nextTick, reactive, ref } from 'vue'
import { getAddedUsers, getDepartments } from '@/http/department'
import type { IDepartment, IDepartmentUser } from '@/http/types/department'
import type { IElTree } from '@/types/element-plus'
import Dialog from '@/components/Dialog/index.vue'

const props = defineProps({
  multiple: {
    type: Boolean,
    default: false
  }
})
interface EmitsType {
  (e: 'success', value: IDepartmentUser[]): void
}
const emit = defineEmits<EmitsType>()

const defaultProps = {
  value: 'id',
  label: 'displayName',
  children: 'children'
}
const data = ref<IDepartment[]>([])
const users = ref<IDepartmentUser[]>([])
const checkedUsers = ref<IDepartmentUser[]>([])

const defaultExpandedKeys = ref<string[]>([])
const formLoading = ref(false)
const tree = ref<IElTree>()
const nodeExpand = (data:any) => {
  defaultExpandedKeys.value.push(data.id)
}
const nodeCollapse = (data:any) => {
  defaultExpandedKeys.value.splice(defaultExpandedKeys.value.indexOf(data.id), 1)
}
const treeCurrentChange = (data:IDepartment) => {
  getUsers(data.id)
}
const handleDialogOpen = async () => {
  formLoading.value = true
  await getData().finally(() => {
    formLoading.value = false
  })
}
const handleDialogClose = () => {
  data.value = []
  users.value = []
  checkedUsers.value = []
  defaultExpandedKeys.value = []
}
const paginationData = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0
})
const getUsers = async (id:string) => {
  const res = await getAddedUsers(
    paginationData.currentPage,
    paginationData.pageSize,
    id
  )
  users.value = res.items
  paginationData.total = res.totalCount
}
const getData = async () => {
  const { items } = await getDepartments()
  data.value = items
  const defaultKeys = data.value.map(e => e.id)
  defaultExpandedKeys.value = defaultExpandedKeys.value.concat(defaultKeys)
  // 默认展示第一节点的数据
  await nextTick()
  tree.value?.setCurrentKey(defaultKeys[0])
  const currentNode = tree.value?.getCurrentNode()
  if (!currentNode) return
  treeCurrentChange(currentNode as IDepartment)
}

const selectUser = (user:IDepartmentUser) => {
  const index = checkedUsers.value.findIndex(e => e.id === user.id)
  if (props.multiple) {
    if (index >= 0) {
      checkedUsers.value.splice(index, 1)
    } else {
      checkedUsers.value.push(user)
    }
  } else {
    checkedUsers.value = [user]
  }
}

const handleConfirm = () => {
  emit('success', checkedUsers.value)
}
</script>

<style scoped lang="scss">
.top{
  height: 400px;
  display: flex;
  justify-content: space-between;
  .left,.right{
    width: 50%;
  }
  .users{
    height: 100%;
    padding: 0 12px;
    .user{
      width: 100%;
      height: 40px;
      border-radius: 3px;
      line-height: 30px;
      padding: 5px;
      display: flex;
      align-items: center;
      &.checked{
        .sign{
          background-color: #3370ff;
        }
      }
      &:hover{
        background-color: #eff0f1;
      }
      .sign{
        display: inline-block;
        width: 16px;
        height: 16px;
        border: 1px solid var(--el-border-color-base);
        margin-right: 8px;
        text-align: center;
        line-height: 16px;
        transition: all .3s;
      }
    }
  }
}
.bottom{
  margin-top: 20px;
  padding: 6px;
  .name{
    line-height: 1.5;
    margin-bottom: 12px;
  }
  .checkedUsers{
    .checkedUser{
      &+.checkedUser{
      margin-left: 10px;
      }
    }
  }
}
</style>
